package com.letianpai.activity;

import java.util.HashMap;
import java.util.Map;

import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.letianpai.R;
import com.letianpai.activity.family.FamilyListActivity;
import com.letianpai.activity.home.ForgetActivity;
import com.letianpai.activity.home.RegsActivity;
import com.letianpai.bean.BackUserinformation;
import com.letianpai.common.tool.StringUtil;
import com.letianpai.db.Constant;
import com.letianpai.db.bean.UserInfo;
import com.letianpai.db.cache.UserCache;
import com.letianpai.http.RequestBean.GetInformation;
import com.letianpai.http.RequestBean.GetInformationBean;
import com.letianpai.http.RequestBean.UserinformationData;
import com.letianpai.utils.ChatUtils;
import com.letianpai.utils.JsonUtil;
import com.letianpai.utils.XmppTool;

public class LoginActivity extends Activity {
	ProgressDialog pd;// 登录的dialog
	View headBackText;
	TextView headShare, headText;
	EditText username, pwd;
	TextView login, getpassword, login_regiest, forget_password;
	public static String account;
	public static String password;
	public static String USERID;
	SharedPreferences sp;
	Editor editor;
	RequestQueue requestQueue;
	public static Bitmap userPhoto;
	public static String nickname;
	public static UserinformationData ui;
	// 清空username、password
	ImageView clear_username, clear_password;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.home_login);
		login_regiest = (TextView) findViewById(R.id.login_regiest);
		forget_password = (TextView) findViewById(R.id.forget_password);
		getpassword = (TextView) findViewById(R.id.password);
		username = (EditText) findViewById(R.id.username);
		pwd = (EditText) findViewById(R.id.password);
		requestQueue = Volley.newRequestQueue(this);
		login = (TextView) findViewById(R.id.login);
		login.setOnClickListener(new LoginClick());
		getpassword.setOnClickListener(new LoginClick());
		login_regiest.setOnClickListener(new LoginClick());
		forget_password.setOnClickListener(new LoginClick());
		clear_username = (ImageView) findViewById(R.id.clear_username);
		clear_password = (ImageView) findViewById(R.id.clear_password);
		clear_username.setOnClickListener(new LoginClick());
		clear_password.setOnClickListener(new LoginClick());
		headBackText = findViewById(R.id.headBackText);
		headBackText.setOnClickListener(new LoginClick());
		headShare = (TextView) findViewById(R.id.headShare);
		headShare.setVisibility(View.INVISIBLE);
		headText = (TextView) findViewById(R.id.headText);
		headText.setText("登录");
	}

	class LoginClick implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			account = username.getText().toString();
			if (StringUtil.isBlank(account)) {
				Toast.makeText(LoginActivity.this, "请您输入用户名",
						Toast.LENGTH_SHORT).show();
				return;
			}
			password = pwd.getText().toString();
			if (StringUtil.isBlank(password)) {
				Toast.makeText(LoginActivity.this, "请您输入密码", Toast.LENGTH_SHORT)
						.show();
				return;
			}

			USERID = account;
			switch (v.getId()) {
			case R.id.headBackText:
				finish();
				break;
			case R.id.password:

				break;
			case R.id.login_regiest:
				Intent intent = new Intent(LoginActivity.this,
						RegsActivity.class);
				startActivity(intent);
				finish();
				break;
			case R.id.forget_password:
				startActivity(new Intent(LoginActivity.this,
						ForgetActivity.class));
				break;
			case R.id.login:

				if (account.equals("") || password.equals("")) {
					mHandler.sendEmptyMessage(1);

				} else {
					pd = new ProgressDialog(LoginActivity.this);
					pd.setTitle("请稍等");
					pd.setMessage("正在登录...");
					pd.show();
					pd.setCanceledOnTouchOutside(false);
					new Thread(new Runnable() {
						@Override
						public void run() {
							try {
								XmppTool.getConnection().login(account,
										password);
								// 状态
								Presence presence = new Presence(
										Presence.Type.unavailable);
								XmppTool.getConnection().sendPacket(presence);
								//
								// Intent intent1 = new Intent();
								// intent1.setClass(LoginActivity.this,
								// FamilyListActivity.class);
								// // intent.setClass(FormLogin.this,
								// // FormClient.class);
								// intent1.putExtra("USERID", USERID);
								// // LetianpaiActivity.tab4.setContent(intent);
								// LoginActivity.this.startActivity(intent1);
								// finish();
								getPhoto();
								mHandler.sendEmptyMessage(2);
							} catch (XMPPException e) {
								new Thread(new Runnable() {

									@Override
									public void run() {
										XmppTool.closeConnection();
									}
								}).start();
								mHandler.sendEmptyMessage(3);
							} catch (IllegalStateException e) {

								XmppTool.closeConnection();

								mHandler.sendEmptyMessage(4);
							}
						}
					}).start();
					new Thread(new Runnable() {

						@Override
						public void run() {
							post();
						}
					}).start();
				}
				break;
			case R.id.clear_username:
				username.setText("");
				break;
			case R.id.clear_password:
				pwd.setText("");
				break;
			default:
				break;
			}
		}

	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				Toast.makeText(LoginActivity.this, "账号或密码不能为空！",
						Toast.LENGTH_SHORT).show();
				break;
			case 2:
				sp = getSharedPreferences("myPref", MODE_WORLD_READABLE);
				// 获取数据后面一个参数表示无返回时的默认值
				editor = sp.edit();
				editor.putString("username", account);
				editor.putString("password", password);
				editor.putString("islogin", "0");
				editor.commit();
				Toast.makeText(LoginActivity.this, "登陆成功！", Toast.LENGTH_SHORT)
						.show();
				pd.cancel();
				Intent intent = new Intent(LoginActivity.this,
						FamilyListActivity.class);
				intent.putExtra("USERID", USERID);
				Window w = TabGroupActivity.group_activity
						.getLocalActivityManager().startActivity("family",
								intent);

				View v = w.getDecorView();
				TabGroupActivity.group_activity.setContentView(v);
				finish();
				break;
			case 3:

				Toast.makeText(LoginActivity.this, "登陆失败！用户名或密码错误！",
						Toast.LENGTH_SHORT).show();
				pd.cancel();
				break;
			case 4:

				Toast.makeText(LoginActivity.this, "连接异常,请检查网络",
						Toast.LENGTH_SHORT).show();
				pd.cancel();
				break;
			default:
				break;
			}
		}
	};

	public void post() {
		Map<String, String> map = new HashMap<String, String>();
		GetInformation userInfo = new GetInformation();
		userInfo.setUsername(LoginActivity.USERID);
		GetInformationBean user = new GetInformationBean();
		user.setHead("getUserInfoServlet");
		user.setContent(userInfo);
		// msg值
		String msg = JsonUtil.objectToString(user, GetInformationBean.class);
		String url = Constant.URL + "?msg=" + msg;
		Log.d("zzzz", url);
		StringRequest request = new StringRequest(url, new ls(), new el());
		requestQueue.add(request);
	}

	// 调用服务器接口发送验证码

	class ls implements Listener<String> {

		@Override
		public void onResponse(String arg0) {
			BackUserinformation br = (BackUserinformation) JsonUtil
					.StringToObject(arg0, BackUserinformation.class);

			if (br.getStatus().equals("SUCCESS")) {
				Toast.makeText(LoginActivity.this, br.getMessage(),
						Toast.LENGTH_SHORT).show();
				ui = br.getData();
				UserInfo user = new UserInfo();
				user.setUsername(ui.getUsername());
				user.setUserId(ui.getUsername());
				user.setNickname(ui.getNickname());
				user.setPassword(password);
				user.setSex(ui.getSex());
				user.setEmail(ui.getEmail());
				user.setLoginType(true);
				UserCache.getInstance().addUser(LoginActivity.this, user);
			}

			if (br.getStatus().equals("FALURE")) {
				Toast.makeText(LoginActivity.this, "获取用户信息失败",
						Toast.LENGTH_SHORT).show();
			}

		}

	}

	class el implements ErrorListener {

		@Override
		public void onErrorResponse(VolleyError arg0) {
			Toast.makeText(LoginActivity.this, "请求失败", Toast.LENGTH_SHORT)
					.show();
		}

	}

	// 获取头像、昵称

	public void getPhoto() {
		try {
			userPhoto = ChatUtils.getUserImage(account);
			nickname = ChatUtils.getname(account);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
